/*
 * @Author: wwssaabb
 * @Date: 2021-11-01 11:18:13
 * @LastEditTime: 2021-11-01 18:01:19
 * @FilePath: \handwritten-code\demo\观察者模式.js
 */

//观察者模式  对象存在一对多的关系

let uid = 0

class Dep {
  constructor() {
    this.uid = uid++
    this.subs = []
  }

  addSub(sub) {
    this.subs.push(sub)
  }

  removeSub(sub) {
    if (this.subs.length) {
      const index = this.subs.findIndex(sub)
      if (index > -1) this.subs.splice(index, 1)
    }
  }

  notify() {
    this.subs.forEach(sub => sub.update())
  }
}

class Watcher {
  constructor(name) {
    this.name = name
  }
  update() {
    console.log(this.name + ' update')
  }
}

//或者
class Watcher {
  constructor(name) {
    this.name = name
  }
  update() {
    console.log(this.name + ' update')
  }
}

class ObserverList {
  constructor() {
    this.observers = []
  }

  add(obs) {
    this.observers.push(obs)
  }

  remove(obs) {
    if (this.observers.length) {
      const index = this.observers.findIndex(i => i === obs)
      if (index > -1) this.observers.splice(index, 1)
    }
  }

  count() {
    return this.observers.length
  }

  clear() {
    this.observers = []
  }

  get(index) {
    return this.observers[index]
  }
}

class Subject {
  constructor() {
    this.observers = new ObserverList()
  }

  addSub(obs) {
    this.observers.add(obs)
  }
}